<template>
  <!-- 顶部数据卡片区，展示四个统计卡片 -->
  <el-row>
    <animated-number-card
      v-for="(item, index) in cardItems"
      :key="`${item.key}-${index}`"
      :title="item.title"
      :icon="item.icon"
      :end-val="item.endVal"
      :start-val="item.startVal"
      :span="6"
      :get-unit="item.getUnit"
      :class="{ 'selected-card': selectedCardIndex === index }"
      @click="() => onCardClick(item.type, index)"
    />
  </el-row>
  <!-- 折线图区域 -->
  <el-row>
    <line-chart :data="lineChartData" />
  </el-row>
  <!-- 表格和便签 -->
  <el-row class="list">
    <Hot></Hot>
  </el-row>
</template>

<script setup>
// 引入 Element Plus 行组件
import { ElRow } from 'element-plus'
// 引入自定义统计卡片和图表组件
import AnimatedNumberCard from '@/components/AnimatedNumberCard.vue'
import LineChart from '@/components/LineChart.vue'
import { User, House, TrendCharts, DataAnalysis, Star, MessageBox, PieChart, Histogram } from '@element-plus/icons-vue'
import axios from 'axios'
import Hot from '@/components/Hot.vue'
import { ref, onMounted, markRaw, onUnmounted, nextTick } from 'vue'

// 图标映射表
const iconMap = {
  star: Star,
  message: MessageBox,
  pie: PieChart,
  histogram: Histogram,
  user: User,
  house: House,
  trend: TrendCharts,
  analysis: DataAnalysis
}

// 卡片数据
const cardItems = ref([
  { title: '总提问数', icon: markRaw(Star), endVal: 0, startVal: 0, getUnit: '次', iconType: 'star', type: 'daily', key: 0 },
  { title: '今日提问', icon: markRaw(MessageBox), endVal: 0, startVal: 0, getUnit: '次', iconType: 'message', type: 'hour', key: 0 },
  { title: '本周提问', icon: markRaw(PieChart), endVal: 0, startVal: 0, getUnit: '次', iconType: 'pie', type: 'week', key: 0 },
  { title: '本月提问', icon: markRaw(Histogram), endVal: 0, startVal: 0, getUnit: '次', iconType: 'histogram', type: 'year', key: 0 }
])

const lineChartData = ref({
  categories: [],
  expected: [],
  actual: [],
  unit: '次'
})

const allStats = ref({})
const selectedType = ref('daily')
const selectedCardIndex = ref(0) // 默认选中第一个卡片

let updateTimer = null

function onCardClick(type, index) {
  selectedType.value = type
  selectedCardIndex.value = index
  updateLineChartData()
}

function updateLineChartData() {
  if (!allStats.value) return
  
  // 创建新的数据对象，确保触发响应式更新
  const newChartData = {
    categories: [],
    actual: [],
    expected: [],
    unit: '次'
  }
  
  if (selectedType.value === 'hour' && allStats.value.hourlyStats) {
    newChartData.categories = allStats.value.hourlyStats.map(i => `${i.hour}时`)
    newChartData.actual = allStats.value.hourlyStats.map(i => i.count)
    newChartData.expected = allStats.value.hourlyStats.map(i => i.count)
    newChartData.unit = '次'
  } else if (selectedType.value === 'week' && allStats.value.weeklyStats) {
    newChartData.categories = allStats.value.weeklyStats.map(i => i.date)
    newChartData.actual = allStats.value.weeklyStats.map(i => i.count)
    newChartData.expected = allStats.value.weeklyStats.map(i => i.count)
    newChartData.unit = '次'
  } else if (selectedType.value === 'month4w' && allStats.value.monthlyStatsByWeek) {
    newChartData.categories = allStats.value.monthlyStatsByWeek.map(i => `第${i.week}周`)
    newChartData.actual = allStats.value.monthlyStatsByWeek.map(i => i.count)
    newChartData.expected = allStats.value.monthlyStatsByWeek.map(i => i.count)
    newChartData.unit = '次'
  } else if (selectedType.value === 'year' && allStats.value.yearlyStats) {
    newChartData.categories = allStats.value.yearlyStats.map(i => i.month)
    newChartData.actual = allStats.value.yearlyStats.map(i => i.count)
    newChartData.expected = allStats.value.yearlyStats.map(i => i.count)
    newChartData.unit = '次'
  } else if (allStats.value.dailyStats) {
    // 默认展示最近30天
    newChartData.categories = allStats.value.dailyStats.map(i => i.date)
    newChartData.actual = allStats.value.dailyStats.map(i => i.count)
    newChartData.expected = allStats.value.dailyStats.map(i => i.count)
    newChartData.unit = '次'
  }
  
  // 使用nextTick确保DOM更新后再更新数据，触发动画
  nextTick(() => {
    lineChartData.value = newChartData
  })
}

const fetchStatistics = async () => {
  try {
    const res = await axios.get('http://localhost:5231/api/QAHistories/statistics')
    const stat = res.data.data
    
    // 保存所有统计数据
    allStats.value = stat
    
    // 更新卡片数据并触发跳动
    const newValues = [
      Number(stat.totalQueries) || 0,
      Number(stat.todayQueries) || 0,
      Number(stat.thisWeekQueries) || 0,
      Number(stat.thisMonthQueries) || 0
    ]
    
    cardItems.value.forEach((item, index) => {
      if (item.endVal !== newValues[index]) {
        item.endVal = newValues[index]
        item.key++ // 增加key值，强制重新渲染
      }
    })

    // 更新折线图数据
    updateLineChartData()
  } catch (e) {
    console.error('获取统计数据失败', e)
  }
}

onMounted(() => {
  fetchStatistics()
  // 每10秒更新一次数据
  updateTimer = setInterval(fetchStatistics, 10000)
})

onUnmounted(() => {
  if (updateTimer) {
    clearInterval(updateTimer)
  }
})
</script>

<style scoped>
/* 小图表区域布局 */
.smallAll {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  margin-top: 2%;
}

.small {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 300px;
  width: 30%;
  min-width: 300px;
}

/* 表格和便签区域布局 */
.list {
  display: flex;
  align-items: flex-start;
  justify-content: space-evenly;
  flex-wrap: wrap;
}

.list>div {
  flex: 1;
  margin: 1%;
}

/* 选中卡片高亮样式 */
:deep(.selected-card) {
  background-color: #e6f7ff !important;
  border-color: #1890ff !important;
  box-shadow: 0 0 8px rgba(24, 144, 255, 0.3) !important;
  transition: all 0.3s ease-in-out !important;
}

:deep(.selected-card:hover) {
  background-color: #bae7ff !important;
}

/* 所有卡片的过渡效果 */
:deep(.box) {
  transition: all 0.3s ease-in-out !important;
}
</style>